package com.lovi.net_.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 监听9999端口，拿到socket对象
 */
public class SocketTCPServer02 {
    public static void main(String[] args) throws IOException {
        //监听端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //程序会阻塞在这，当9999端口被连接的时候，我们拿到连接9999的socket对象
        System.out.println("服务器端已经启动，等待连接...");
        Socket accept = serverSocket.accept();
        //服务器端读取客户发送过来的东西
        InputStream inputStream = accept.getInputStream();
        byte[] b = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(b))!=-1){
            System.out.println(new String(b,0,readLen));
        }
        //读取到之后发消息给客户端
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("服务器端：你好，我是服务器端".getBytes());
        accept.shutdownOutput();//结束标记
        outputStream.close();
        inputStream.close();
        accept.close();
        System.out.println("服务器端关闭！");
    }
}
